<template>
  <div class="form-product">
    <!-- 添加按钮 S -->
    <el-button
      class="add-subform-btn"
      icon="el-icon-plus"
      @click="handleClickAddProduct"
    >
      {{$t('common.base.addModule', {module:''})}}
    </el-button>

    <el-button
      v-if="supportCreate"
      @click="handleAddProduct"
    >
      {{$t('common.base.create', {module:''})}}
    </el-button>
    <!-- 添加按钮 E -->

    <!-- 产品表单表格 S -->
    <el-table
      v-table-style
      :data="productFieldsValues"
      header-row-class-name="common-list-table-header__v2"
      border
    >
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :min-width="column.minWidth || '108px'"
        :show-overflow-tooltip="column.field !== 'name'"
      >
        <template slot-scope="scope">
          <template v-if="column.setting.originalFormType === 'address'">
            {{ getAddress(scope.row[column.field]) }}
          </template>
          <template v-else-if="column.setting.originalFormType === 'user'">
            {{ getUser(scope.row[column.field]) }}
          </template>
          <template v-else-if="column.setting.originalFormType === 'cascader'">
            {{ scope.row[column.field] | fmt_form_cascader(column.setting.isMulti, column.setting.displayMode) }}
          </template>
          <template v-else-if="column.setting.originalFormType === 'location'">
            {{ getLocation(scope.row[column.field]) }}
          </template>
          <template v-else-if="column.fieldName === 'serviceMoney' && internationalGray">
            {{ montageCurrency(scope.row, column) }}
          </template>
          <template v-else>
            {{
              $formatFormField(column, scope.row)
            }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100">
        <template slot-scope="scope">
          <span class="color-primary pub_btn mr_12" @click="editProductFieldValue(scope.row, scope.$index)">{{ $t('common.base.edit') }}</span>
          <span class="color-danger pub_btn" @click="deleteProductFieldValue(scope.$index)">{{ $t('common.base.delete') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 产品表单表格 E -->

    <!-- 添加子表单数据弹窗 S -->
    <base-modal :title="title" :show.sync="visible" width="600px">
      <form-builder
        v-if="visible"
        ref="form"
        :fields="subFields"
        :value="form"
        @update="update"
      >
        <!-- 产品名称 S -->
        <template slot="name" slot-scope="{ field, value }">
          <form-item :label="field.displayName">
            <biz-form-remote-select
              :field="field"
              v-model="selectedProduct"
              :remote-method="searchProcuct"
              @input="updateSubProduct"
              :placeholder="$t('common.placeholder.select')"
              v-if="action === 'create'"
            >
              <div
                class="product-template-option"
                slot="option"
                slot-scope="{ option }"
              >
                <h3>{{ option.name }}</h3>
                <div class="product_item">
                  <div
                    v-for="item in customerRelationProductField"
                    :key="item.fieldName"
                    class="product_item_sub"
                  >
                    <label>{{ item.displayName }}：</label>
                    <span>{{ $formatFormField(item, option) }}</span>
                  </div>
                  <div class="product_item_sub">
                    <label>{{$t('common.form.type.customer')}}：</label>
                    <span v-if="option.customer && option.customer.id">{{
                      option.customer.name
                    }}</span>
                    <span class="customer-unbind-name" v-else>{{$t('common.base.notContact')}}</span>
                  </div>
                </div>
              </div>
            </biz-form-remote-select>
            <form-text :field="field" :value="value" v-else />
          </form-item>
        </template>
        <!-- 产品名称 E -->

        <!-- 服务金额 S -->
        <template slot="serviceMoney" slot-scope="{ field, value }">
          <form-item :label="field.displayName" :validation="true">
            <div class="form-item-price">
              <form-number :field="field" :value="value" @update="e => update(e)"></form-number>
              <form-currency-type 
                v-if="internationalGray"
                :value="form.serviceMoneyCurrency"
                @input="e => currencyHandleChange(e, field)"
              ></form-currency-type>
            </div>
          </form-item>
        </template>
        <!-- 服务金额 E -->
      </form-builder>
      <div slot="footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
    <!-- 添加子表单数据弹窗 E -->

    <!-- 质保权益弹框 -->
    <warranty-interest-dialog
      ref="dialogRef"
      :dataList="productArr"
      :isCreateOrEffect="isCreateOrEffect"
      @handleUpdateQualityTime="handleUpdateQualityTime"
    ></warranty-interest-dialog>
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* util */
import * as FormUtil from '@src/component/form/util';
import { CURRENCY_SUFFIX } from '@src/util/currency';
/** api */
import { getCustomerLinkProduct } from '@src/api/ContractApi';
/* service */
import { smoothQualityInfoFieldForTable } from '@service/QualityInfoService';
/** emun */
import { QualityStateEnum } from '@model/enum/QualityInfoEnum';

import { SUBFORM_FIELDS_ADD_LENGTH_MAX } from '@src/component/form/config';
/* components */
import FormCurrencyType from '@src/component/form/components/FormCurrencyType/FormCurrencyType.vue';
import WarrantyInterestDialog from '@src/modules/contract/components/WarrantyInterestDialog.vue';
import _ from 'lodash';

import { Message } from 'element-ui';
import { fmt_form_cascader } from '@src/filter/form'

import { options } from '@src/modules/contract/contractList/fields.js';
import { formatAddress, formatDate, useFormTimezone } from 'pub-bbx-utils';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
import EventBus from '@src/util/eventBus';
const { internationalGray } = useFormMultiLanguage();

export default {
  name: 'form-product',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  inject: ['configData'],
  components: {
    WarrantyInterestDialog,
    [FormCurrencyType.name]: FormCurrencyType
  },
  data() {
    return {
      action: 'create',
      visible: false,
      currentProductIndex: null,
      productFieldsValues: [],
      form: {},
      selectedProduct: [], // 当前选中的产品
      productArr: []
    };
  },
  computed: {
    isCreateSubform() {
      return this.action === 'create';
    },
    actionText() {
      return this.action == 'create' ? this.$t('common.base.addModule', {module:''}) : this.$t('common.base.edit');
    },
    // 标题
    title() {
      return `${this.actionText}${this.field?.displayName || ''}`;
    },
    // 表头
    subFieldHeader() {
      let arr = this.field?.subFormFieldList || [];
      return smoothQualityInfoFieldForTable(arr || []);
    },
    // 产品表格表头
    columns() {
      let columns = this.subFieldHeader;

      columns.map(field => {
        field.label = field.displayName;
        field.field = field.fieldName;
      });

      return columns;
    },
    // 产品表单数据
    subFields() {
      let fields = this.subFieldHeader;

      fields.forEach(item => {
        if (this.action == 'create' && item.fieldName == 'name') {
          item.isNull = 0;
          item.formType = 'select';
          item.disabled = false;
        }
        if (item.formType == 'relateProduct') {
          item.isNull = 1;
        }
        if (this.action == 'edit' && item.fieldName == 'name') {
          item.disabled = true;
        }
        if (
          item.fieldName === 'qualityInfoStartTime' ||
          item.fieldName === 'qualityInfoEndTime' ||
          item.fieldName === 'qualityInfoStatus'
        ) {
          item.formType = 'relateProduct';
        }
      });

      return fields;
    },
    // 客户关联的产品
    customerRelationProductField() {
      let newFields = this.subFieldHeader;

      const fields = newFields.filter(
        f => f.fieldName == 'catalogId' || f.fieldName == 'serialNumber'
      );

      return fields;
    },
    // 需要检验重复性的表单
    checkFieldMap() {
      let repeatFields = this.subFields.filter(f => {
        const { isRepeat } = f.setting || {};
        if (!!isRepeat) return f;
      });

      return repeatFields;
    },
    /* 客户字段 */
    customerField() {
      let { fields = [] } = this.formBuilderComponent;
      return fields.find(field => field.formType == 'customer');
    },
    /* 客户 */
    customer() {
      if (!this.customerField) return {};

      let { fieldName } = this.customerField;
      let customer = this.formValue[fieldName] || '';

      return customer;
    },
    _configData() {
      return this.configData?.proQualityInfo || {};
    },
    // 开始
    qualityStartDateMapping() {
      return this._configData?.qualityStartDate?.fieldName|| '';
    },
    // 结束
    qualityEndDateMapping() {
      return this._configData?.qualityEndDate?.fieldName|| '';
    },
    // 合同 更新产品质保信息是否开启 && 按合同中产品服务时间字段 PRODUCT_SERVICE_DATE
    ifCheckSyncProduct() {
      return !!this._configData?.productQualitySwitch && this._configData?.productQualityCondition2 === 'PRODUCT_SERVICE_DATE';
    },
    // 合同创建 还是 合同生效
    isCreateOrEffect() {
      const result = (options || []).filter(item => item.value === this._configData?.productQualityCondition1)
      return result[0]?.label || '';
    },
    internationalGray() {
      return internationalGray;
    },
    currencySuffix() {
      return CURRENCY_SUFFIX;
    },
    supportCreate() {
      return this.configData?.productSupportCreate || false
    }
  },
  watch: {
    value(newValue) {
      this.productFieldsValues = (newValue || []).map(item => {
        item.catalogId = item.catalog?.pathName || '';

        return {
          ...item,
        };
      });
    },
    visible(newValue) {
      if(newValue) this.getProductCurrency();
    }
  },
  methods: {
    handleAddProduct() {
      EventBus.$emit('form-product-add')
    },
    // 更新表格数据
    updateTableData() {
      // 新增表单
      if (this.isCreateSubform) {
        this.productFieldsValues.push(this.form);
      } else {
        // 编辑表单
        this.$set(
          this.productFieldsValues,
          this.currentProductIndex,
          this.form
        );
      }

      this.visible = false;
      this.inputForValue(this.productFieldsValues);
    },
    // 同步更新质保时间
    handleUpdateQualityTime(syncProduct) {
      if (syncProduct) {
        let start = new Date(this.productArr[0]?.afterValue).getTime();
        let end = new Date(this.productArr[1]?.afterValue).getTime();
        if (start > end) {
          this.$refs.dialogRef.visible = false;
          return Message({
            message: this.$t('common.base.tip.endTimeMustLastThanStartTitem'),
            type: 'error',
            customClass: 'messageZindex',
          });
        }
      }

      this.form['syncProduct'] = !!syncProduct;
      this.updateTableData();
      this.$refs.dialogRef.visible = false;
      this.productArr = [];
    },
    // 重置数据
    resetForm() {
      this.selectedProduct = [];
      this.currentProductIndex = null;
      this.form = FormUtil.initialize(this.subFields, {});
    },
    // 点击添加
    handleClickAddProduct() {
      if (!this.customer) return this.$message.warning(this.$t('common.form.tip.chooseBeforeTips', {module:this.$t('common.form.type.customer')}));

      if (this.productFieldsValues.length >= SUBFORM_FIELDS_ADD_LENGTH_MAX)
        return this.$message.warning(this.$t('common.form.tip.alowAddDataCount', {data1:SUBFORM_FIELDS_ADD_LENGTH_MAX}));

      this.action = 'create';
      this.visible = true;
      this.resetForm();
    },
    // 编辑表单
    editProductFieldValue(value, index) {
      this.action = 'edit';
      this.currentProductIndex = index;
      this.form = Object.assign({}, this.processData(value));
      this.visible = true;
      this.selectedProduct = [];
    },
    // 删除表单
    deleteProductFieldValue(index) {
      this.productFieldsValues.splice(index, 1);
      this.inputForValue(this.productFieldsValues);
    },

    /**
     * @description 搜索产品
     */
    async searchProcuct(params = {}) {
      params.customerId = this.customer[0].id;
      return this.fetchProductList(params);
    },
    async fetchProductList(params = {}) {
      try {
        let result = {};

        let res = await getCustomerLinkProduct(params);
        if (!res.success) return;

        result = res.result;

        result.list = result.list.map(product => {
          return Object.freeze({
            label: product.name,
            value: product.id,
            name: product.name,
            ...product,
            ...product?.attribute,
            catalogId: product.catalog.pathName,
            qualityInfoStartTime: product.qualityStartTime,
            qualityInfoEndTime: product.qualityEndTime,
            qualityInfoStatus: QualityStateEnum[product.qualityStatus],
          });
        });
        return result;
      } catch (error) {
        console.warn('task-edit-form: searchProduct -> error', error);
      }
    },

    // 特殊数据处理
    getAddress(fieldVal) {
      // let address = fieldVal?.province + fieldVal?.city + fieldVal?.dist + fieldVal?.address || '';
      // return fieldVal?.all || address;
      return formatAddress(fieldVal)

    },
    getUser(fieldVal) {
      return Array.isArray(fieldVal)
        ? fieldVal.map(v => v.displayName).join(',')
        : fieldVal?.displayName || fieldVal || '';
    },
    // 位置
    getLocation(fieldVal) {
      return fieldVal?.address || fieldVal || '';
    },
    // 数据处理
    processData(params) {
      let formObj = {
        ...params
      };
      formObj['id'] = params.id;
      formObj['syncProduct'] = false;
      formObj['catalog'] = params.catalog;

      this.subFields.map(field => {
        let fieldName = field.fieldName;
        let formType = field.setting.originalFormType;

        // 产品子表单目前都是以input展示，所以有些数据需要特殊处理
        let fieldVal = params[fieldName]; // 表单的值

        if (formType === 'address') {
          formObj[fieldName] = this.getAddress(fieldVal);
        } else if (formType === 'user') {
          formObj[fieldName] = this.getUser(fieldVal);
        } else if (formType === 'cascader') {
          formObj[fieldName] = fmt_form_cascader(fieldVal, field.setting?.isMulti, field.setting?.displayMode);
        } else if (formType === 'location') {
          formObj[fieldName] = this.getLocation(fieldVal);
        } else if (['qualityInfoStartTime', 'qualityInfoEndTime'].includes(fieldName)) {
          formObj[fieldName] = formatDate(fieldVal || '', 'date')
        } else {
          formObj[fieldName] = fieldVal || '';
        }
      });

      return formObj;
    },
    /**
     * @description 选择产品
     */
    updateSubProduct(value) {
      let newValue = value[0];
      if (!newValue) return;
      this.form = Object.assign({}, this.processData(newValue));
      this.getProductCurrency();
    },
    /**
     * @description: 提交表单
     */
    async onSubmit() {
      // 校验表单必填项
      const validateRes = await this.$refs.form.validate(false);
      if (!validateRes) return;

      // 重复性表单校验
      let validateField = this.repeatRemoteValidate(this.currentProductIndex);
      if (validateField) return this.$message.warning(validateField);

      // 校验产品是否添加重复
      let isExit = (this.productFieldsValues || []).some(
        v => v?.id == this.form.id
      );
      if (isExit && this.isCreateSubform)
        return this.$message.warning(this.$t('common.base.tip.notAddRepeatedlyModule2', {module:this.$t('common.form.type.product')}));

      // 产品质保权益的开关是开着的
      if (this.ifCheckSyncProduct) {
        this.$refs.dialogRef.visible = true;
        // TODO 下面时间格式临时先默认date，应该具体使用field的格式判断 可以使用getFormDateFormat
        // 这里有点疑问：表单内显示的是(服务开始时间)，但是这里用了固定翻译(质保开始时间)不一致
        this.productArr = [
          {
            serialNumber: this.form?.serialNumber || '',
            name: this.form?.name || '',
            updateText: this.$t('common.form.preview.qualityInfo.qualityStartDate'),
            beforeValue: formatDate(this.form?.qualityInfoStartTime || '', 'date'),
            afterValue: formatDate(this.form?.[this.qualityStartDateMapping] || '', 'date'),
          },
          {
            serialNumber: this.form?.serialNumber || '',
            name: this.form?.name,
            updateText: this.$t('common.form.preview.qualityInfo.qualityEndDate'),
            beforeValue: formatDate(this.form?.qualityInfoEndTime || '', 'date'),
            afterValue: formatDate(this.form?.[this.qualityEndDateMapping] || '', 'date'),
          },
        ];
      } else {
        this.handleUpdateQualityTime(false);
      }
    },

    // 更新表单数据
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      this.$set(this.form, fieldName, newValue);
    },
    // 货币选择变化
    currencyHandleChange(val, field) {
      const fieldName = field.fieldName + this.currencySuffix;
      this.update({ field: { fieldName }, newValue: val });
    },
    // 产品表格中的金额添加币种
    montageCurrency(row, column) {
      const currencyField = column.field + this.currencySuffix;
      return `${row[column.field]} ${(row[currencyField] || 'CNY')}`;
    },
    getProductCurrency() {
      if(this.internationalGray && !this.form?.serviceMoneyCurrency) {
        const serviceMoneyItem = this.subFieldHeader.find(x => x.fieldName === 'serviceMoney');
        this.$set(this.form, 'serviceMoneyCurrency', serviceMoneyItem.setting?.defaultCurrency || 'CNY')
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.form-product {
  .add-subform-btn {
    color: $color-primary;
    border-color: #b8eded;
    background-color: $color-primary-light-1;
    margin-bottom: 12px;
    &:hover {
      background: $color-primary-light-6;
      border-color: $color-primary-light-6;
      color: #fff;
    }
  }
}
.product-template-option {
  font-size: 12px;
  padding: 10px 0;
  h3 {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 24px;
    margin-bottom: 0;
  }
  .product_item {
    &_sub {
      line-height: 24px;
    }
    .customer-unbind-name {
      color: #bfbfbf;
    }
  }
}

.pub_btn {
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}

.form-item-price {
  display: flex;
  width: 100%;
  .form-number {
    width: 100%;
  }
  .form-text {
    width: 40%;
    margin-left: 6px;

    ::v-deep .el-select {
      width: 100%;
    }
  }

  .contract-price {
    width: 30%;
  }
}
</style>